/**
 *@Author: QWP
 *@Description: 登录时获取基础信息
 *@Date 2025-01-09 11:21
 */
import { useBaseStore } from "@/store";
import * as enum_types from "@/store/busi/base_type";
import * as enumApi from "@/service/enum";
import * as userApi from "@/service/system/user";
import { evectionUserTree } from "@/service/administration/travel";
import * as unitApi from "@/service/system/unit";
import { cloneDeep } from "lodash";

interface InitBaseDataOptions {
  userData: any;
}
class InitBaseData {
  constructor(private options: InitBaseDataOptions) {}

  private baseStore: any = new useBaseStore();

  // 全部调用
  public getAll = (): void => {
    this.getBaseData();
    this.getProcessBusi();
    this.getDeptData(this.options.userData["unitId"]);
    // this.getDeptUsers(this.options.userData)
    this.getUnitTree();
  };

  // 获取基础数据
  private getBaseData = async () => {
    try {
      const result = await enumApi.enums({ types: Object.values(enum_types).join(",") });
      if (result.code == 0) {
        Object.values(enum_types).forEach((k) => {
          this.baseStore["set_" + k](result.data[k] || []);
        });
      }
    } catch (error) {}
  };

  // 获取所有有流程的业务枚举
  private getProcessBusi = async () => {
    try {
      const res = await enumApi.modAndbill();
      if (res.code == 0) {
        this.baseStore.setModAndbill(res.data || []);
      }
    } catch (error) {}
  };

  // 获取登录人单位的部门数据
  private getDeptData = async (id: string) => {
    try {
      const result = await userApi.tree(id);
      if (result.code == 0) {
        let tData = result.data || [];
        // 部门人员树
        this.baseStore.setDeptUsers(cloneDeep(tData));

        tData.forEach((item: any) => {
          item.value = item.keyid;
          item.label = item.name;
          item.node_type = item.nodeType;
          delete item["children"];
          delete item["nodeType"];
        });
        // 部门树形
        this.baseStore.setDeptData(tData);
      }
    } catch (error) {}
  };

  // 获取部门人员数据
  private getDeptUsers = async (data: any) => {
    try {
      const result = await evectionUserTree(data["unitId"]);
      if (result.code == 0) {
        let tDataJSon = JSON.stringify(result.data || []).replace(/nodeType/g, "node_type");
        this.baseStore.setDeptUsers(JSON.parse(tDataJSon));
      }
    } catch (error) {}
  };

  // 获取单位树形
  private getUnitTree = async () => {
    try {
      const res = await unitApi.validTree();
      if (res.code == 0) {
        this.baseStore.setUnitData(res.data || []);
      }
    } catch (error) {}
  };
}

export default function useInitBaseData(options: InitBaseDataOptions) {
  const initGetBaseData = new InitBaseData(options);
  return {
    getAllBase: initGetBaseData.getAll,
  };
}
